//
//  SearchViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/1.
//

#import "SearchViewController.h"
#import "SearchHistoryCollectionViewCell.h"
#import "LeftAlignedCollectionViewFlowLayout.h"
#import "MyCollectionListCell.h"
#import <AVFoundation/AVFoundation.h>
#import "SearchWordManager.h"
#import "WordListModel.h"
#import "WordDetialViewController.h"
#import "JPNavigationController.h"
#import "nuisdk/NeoNuiTts.h"
#import "AudioController.h"
#import <AdSupport/ASIdentifierManager.h>
#import "GetALiYunTokenManager.h"
#import "NeoNuiTtsManager.h"

@interface SearchViewController ()<
UITextFieldDelegate,
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout,
UITableViewDelegate,
UITableViewDataSource,
///AVSpeechSynthesizerDelegate,
JPAPIManagerCallBackDelegate,
ConvVoiceRecorderDelegate,
NeoNuiTtsDelegate
>

@property(nonatomic,strong)UITextField *searchTF;
@property(nonatomic,strong)UILabel *historyTipLabel;
@property(nonatomic,strong)UIButton *deleteBtn;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *historyArr;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *resultArr;
@property(nonatomic,strong)MyCollectionListCell *currentCell;
@property(nonatomic,assign)NSInteger playIndex;
//@property(nonatomic,strong)AVSpeechSynthesizer *synthesizer;
@property(nonatomic,strong)SearchWordManager *searchWordManager;
@property(nonatomic,strong)NeoNuiTts *nui;
@property(nonatomic,strong)AudioController *audioController;
@property (nonatomic, strong) dispatch_queue_t work_queue;
@property(nonatomic,strong)GetALiYunTokenManager *aLiYunTokenManager;
@property(nonatomic,strong)UIButton *chineseBtn;
@property(nonatomic,strong)UIButton *jpanBtn;
@property(nonatomic,strong)AVPlayer *avPlayer;
@property (nonatomic,assign)BOOL isPlaying;

@end

@implementation SearchViewController

-(NSMutableArray *)historyArr{
    if(!_historyArr){
        _historyArr = [NSMutableArray array];
    }
    return _historyArr;
}

-(NSMutableArray *)resultArr{
    if(!_resultArr){
        _resultArr = [NSMutableArray array];
    }
    return _resultArr;
}

-(SearchWordManager *)searchWordManager{
    if(!_searchWordManager){
        _searchWordManager = [[SearchWordManager alloc]init];
        _searchWordManager.delegate = self;
    }
    return _searchWordManager;
}

-(GetALiYunTokenManager *)aLiYunTokenManager{
    if(!_aLiYunTokenManager){
        _aLiYunTokenManager = [[GetALiYunTokenManager alloc]init];
        _aLiYunTokenManager.delegate = self;
    }
    return _aLiYunTokenManager;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    self.playIndex = -1;
    NSArray *arr = [[NSUserDefaults standardUserDefaults]objectForKey:@"searchHistoryArr"];
    if(arr){
        self.historyArr = [NSMutableArray arrayWithArray:arr];
    }
    
    [self createUI];
    
    [self initPlay];
    [self NuiTtsInit];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(wordDetialCollectRefresh:) name:@"WordDetialCollectRefresh" object:nil];
    
    //听力播放结束
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playToEndTime:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 重新设置 delegate 确保回调正常工作
    if (self.nui){
        self.nui.delegate = self;
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
            }
        });
    }
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
    
    if(self.avPlayer&&self.isPlaying == YES){
        [self.avPlayer pause];
        self.isPlaying = NO;
    }
    
}


#pragma mark - 语音合成播放需要
-(void)initPlay{
    
    self.audioController = [[AudioController alloc] init:only_player];
    self.audioController.delegate = self;
    [self.audioController setPlayerSampleRate:16000];// 16000返回音频的采样率
    
    self.work_queue = dispatch_queue_create("SearchViewController_WorkQueue", DISPATCH_QUEUE_CONCURRENT);
    
}

#pragma mark - 语音合成初始化
-(void)NuiTtsInit{
    if (self.nui == NULL||self.nui == nil) {
        self.nui = [NeoNuiTtsManager sharedManager].nui;
        self.nui.delegate = self;
    }
    //请注意此处的参数配置，其中账号相关需要按照genInitParams的说明填入后才可访问服务
    NSString * initParam = [self genInitParams];
    int retcode = [self.nui nui_tts_initialize:[initParam UTF8String] logLevel:LOG_LEVEL_VERBOSE saveLog:YES];
    
    NSString *fontName = @"tomoka";
    [self.nui nui_tts_set_param:"font_name" value:[fontName UTF8String]];
    //在线合成
    [self.nui nui_tts_set_param:"mode_type" value:"2"]; // 必填
    NSString *speed_level = @"1";
    [self.nui nui_tts_set_param:"speed_level" value:[speed_level UTF8String]];
    NSString *pitch_level = @"0";
    [self.nui nui_tts_set_param:"pitch_level" value:[pitch_level UTF8String]];
    NSString *volume = @"2";
    [self.nui nui_tts_set_param:"volume)" value:[volume UTF8String]];
    // 字级别音素边界功能开关，该参数只对支持字级别音素边界接口的发音人有效。“1”表示打开，“0”表示关闭。
    [self.nui nui_tts_set_param:"enable_subtitle" value:"1"];
    
    if (retcode != 0) {
         TLog(@"init failed.retcode:%d", retcode);
         return;
    }
    
}

-(NSString *)genInitParams{
    NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"];
    NSString *bundlePath = [[NSBundle bundleWithPath:strResourcesBundle] resourcePath];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"voices"];
    // 创建目录
    BOOL res=[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        TLog(@"文件夹创建成功");
    }else{
        TLog(@"文件夹创建失败");
    }
    NSString *debug_path = testDirectory;
    NSMutableDictionary *ticketJsonDict = [NSMutableDictionary dictionary];
    [ticketJsonDict setObject:ALIYUNYUYINKEY forKey:@"app_key"];
    [self checkToken];
    NSString *TOKEN = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(!TOKEN){
        TOKEN = @"";
    }
    [ticketJsonDict setObject:TOKEN forKey:@"token"];
    
    //工作目录路径，SDK从该路径读取配置文件
    [ticketJsonDict setObject:bundlePath forKey:@"workspace"]; // 必填, 且需要有读写权限
//    TLog(@"workspace:%@", bundlePath);
    [ticketJsonDict setObject:debug_path forKey:@"debug_path"];
//    TLog(@"debug_path:%@", debug_path);

    [ticketJsonDict setObject:@"wss://nls-gateway.aliyuncs.com/ws/v1" forKey:@"url"]; // 默认

    // 设置成在线语音合成模式, 这个设置很重要, 遗漏会导致无法运行
    [ticketJsonDict setObject:@"2" forKey:@"mode_type"]; // 必填
    
    NSString *id_string = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//    TLog(@"id: %s", [id_string UTF8String]);
    [ticketJsonDict setObject:id_string forKey:@"device_id"]; // 必填, 推荐填入具有唯一性的id, 方便定位问题

    NSData *data = [NSJSONSerialization dataWithJSONObject:ticketJsonDict options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}

#pragma mark - 获取token
-(void)checkToken{
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(token){
        //token 存在 判断时间
        NSString *expireTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_EXPIRETIME"];
        if(expireTime){
            NSDate *currentDate = [NSDate date];
            NSTimeInterval expireTimeInterval = [expireTime doubleValue];
            NSDate *expireDate = [NSDate dateWithTimeIntervalSince1970:expireTimeInterval];
            if ([currentDate compare:expireDate] != NSOrderedAscending) {
                // 当前时间等于或在过期时间之后 已经到了过期时间
                [self.aLiYunTokenManager loadData];

            } else {
                // 当前时间在过期时间之前 还没到过期时间
            }
        }else{
            [self.aLiYunTokenManager loadData];
        }
    }else{
        [self.aLiYunTokenManager loadData];
    }
}


#pragma mark - 单词详情改变了收藏状态
-(void)wordDetialCollectRefresh:(NSNotification*)notifi{
    if(notifi.object){
        WordListModel *model = notifi.object;
        for(NSInteger i = 0;i < self.resultArr.count;i++){
            WordListModel *model2 = self.resultArr[i];
            if([model.wordId isEqualToString:model2.wordId]){
                [self.resultArr replaceObjectAtIndex:i withObject:model];
                break;
            }
        }
        [self.tableView reloadData];
    }
}

#pragma mark - 界面
-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    self.searchTF = [[UITextField alloc]init];
    self.searchTF.backgroundColor = UIColorHex_(0xffffff,0.6);
    self.searchTF.layer.cornerRadius = 18;
    self.searchTF.layer.masksToBounds = YES;
    self.searchTF.layer.borderWidth = 1.0;
    self.searchTF.layer.borderColor = KThemeColor.CGColor;
    self.searchTF.tintColor = KThemeColor;
    self.searchTF.font = JPUIFontPingFangSCRegular(14);
    self.searchTF.textColor = KFontGrayColor;
    self.searchTF.returnKeyType = UIReturnKeySearch;
    self.searchTF.delegate = self;
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0,0,42,40)];
    UIImageView *logoImageView = [[UIImageView alloc]initWithFrame:CGRectMake(17,12.5,15,15)];
    logoImageView.image = [UIImage imageNamed:@"area_search"];
    [leftView addSubview:logoImageView];
    self.searchTF.leftView = leftView;
    self.searchTF.leftViewMode = UITextFieldViewModeAlways;
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 55,40)];
    UIView *rightBgView = [[UIView alloc]initWithFrame:CGRectMake(5,10,39,20)];
    rightBgView.layer.cornerRadius = 2;
    rightBgView.layer.masksToBounds = YES;
    rightBgView.layer.borderColor = KThemeColor.CGColor;
    rightBgView.layer.borderWidth = 1;
    [rightView addSubview:rightBgView];
    self.chineseBtn = [[UIButton alloc]initWithFrame:CGRectMake(1,1,18,18)];
    [self.chineseBtn setTitle:@"中" forState:UIControlStateNormal];
    self.chineseBtn.titleLabel.font = JPUIFontPingFangSCMedium(10);
    [self.chineseBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.chineseBtn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
    [self.chineseBtn addTarget:self action:@selector(chineseBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [rightBgView addSubview:self.chineseBtn];
    self.chineseBtn.selected = NO;
    self.jpanBtn = [[UIButton alloc]initWithFrame:CGRectMake(20,1,18,18)];
    [self.jpanBtn setTitle:@"日" forState:UIControlStateNormal];
    self.jpanBtn.titleLabel.font = JPUIFontPingFangSCMedium(10);
    [self.jpanBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.jpanBtn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
    [self.jpanBtn addTarget:self action:@selector(jpanBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [rightBgView addSubview:self.jpanBtn];
    self.jpanBtn.selected = YES;
    self.jpanBtn.backgroundColor = KThemeColor;
    self.searchTF.rightView = rightView;
    self.searchTF.rightViewMode = UITextFieldViewModeAlways;
    NSMutableAttributedString *pStr = [[NSMutableAttributedString alloc]initWithString:@"查询中文或日文"];
    [pStr addAttribute:NSForegroundColorAttributeName value:KFontGrayColor range:NSMakeRange(0,pStr.length)];
    [pStr addAttribute:NSFontAttributeName value:JPUIFontPingFangSCRegular(14) range:NSMakeRange(0,pStr.length)];
    self.searchTF.attributedPlaceholder = pStr;
    [self.customNavigationBar addSubview:self.searchTF];
    [self.searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@52);
        make.right.mas_equalTo(@-64);
        make.bottom.mas_equalTo(@-3);
        make.height.mas_equalTo(@36);
    }];
    [self.searchTF addTarget:self action:@selector(textChange) forControlEvents:
      UIControlEventEditingChanged];
    
    __weak typeof(self)weakSelf = self;
    UIButton *cancelBtn = [[UIButton alloc]init];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = JPUIFontPingFangSCRegular(16);
    [cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(@42);
        make.height.mas_equalTo(@42);
        make.centerY.mas_equalTo(weakSelf.searchTF);
        make.right.mas_equalTo(@-11);
    }];
    
    self.historyTipLabel = [[UILabel alloc]init];
    self.historyTipLabel.font = JPUIFontPingFangSCMedium(15);
    self.historyTipLabel.textColor = KFontBlackColor;
    self.historyTipLabel.text = @"历史搜索";
    [self.view addSubview:self.historyTipLabel];
    [self.historyTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+19);
        make.height.mas_equalTo(@21);
    }];
    
    self.deleteBtn = [[UIButton alloc]init];
    [self.deleteBtn setImage:[UIImage imageNamed:@"search_delete"] forState:UIControlStateNormal];
    [self.deleteBtn addTarget:self action:@selector(deleteBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.deleteBtn];
    [self.deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-6);
        make.width.height.mas_equalTo(@40);
        make.centerY.mas_equalTo(weakSelf.historyTipLabel);
    }];
    
    LeftAlignedCollectionViewFlowLayout *flowLayout = [[LeftAlignedCollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 12; // 设置最小的 item 间距为 12
    flowLayout.minimumLineSpacing = 12; // 设置行间距为 12
    flowLayout.sectionInset = UIEdgeInsetsMake(16, 16, 16, 16); // 设置 section 的内边距
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+42,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-42) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[SearchHistoryCollectionViewCell class] forCellWithReuseIdentifier:@"SearchHistoryCollectionViewCell"];
    [self.view addSubview:self.collectionView];

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 90;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:NSClassFromString(@"MyCollectionListCell") forCellReuseIdentifier:@"MyCollectionListCell"];
    [self.view addSubview:self.tableView];
    self.tableView.hidden = YES;
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         // 获取当前可用宽度并更新布局
         self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
         self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
         self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
         self.collectionView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+42,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-42);
         [self.collectionView reloadData];
         self.tableView.frame = CGRectMake(0, kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
         [self.tableView reloadData];
            
            
        });
    }
}

#pragma mark - 切换中文
-(void)chineseBtnClick{
    self.chineseBtn.selected = YES;
    self.chineseBtn.backgroundColor = KThemeColor;
    self.jpanBtn.backgroundColor = [UIColor whiteColor];
    self.jpanBtn.selected = NO;
    if(self.searchTF.text.length > 0){
        [self searchData];
    }
}

#pragma mark - 切换日文
-(void)jpanBtnClick{
    self.jpanBtn.selected = YES;
    self.jpanBtn.backgroundColor = KThemeColor;
    self.chineseBtn.backgroundColor = [UIColor whiteColor];
    self.chineseBtn.selected = NO;
    if(self.searchTF.text.length > 0){
        [self searchData];
    }
}

#pragma mark - collectionview
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchHistoryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SearchHistoryCollectionViewCell" forIndexPath:indexPath];
    cell.text = self.historyArr[indexPath.item];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *text = self.historyArr[indexPath.item];
    NSString *language = [self detectLanguageForText:text];
    UIFont *font = JPUIFontPingFangSCRegular(14);
    if([language isEqualToString:@"ja-JP"]||[language isEqualToString:@"ja"]){
        font = JPUIFontNotoSansJPRegular(14);
    }
    CGFloat maxWidth = collectionView.bounds.size.width - 32;
    CGSize constraintSize = CGSizeMake(maxWidth, CGFLOAT_MAX);
    CGRect boundingBox = [text boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    CGFloat width = MIN(boundingBox.size.width + 20, maxWidth);
    CGFloat height = boundingBox.size.height + 8;
    return CGSizeMake(width, height);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.historyArr.count;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(16, 16, 16, 16);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 12; // 设置 item 之间的最小间距
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 12; // 设置行间距
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = self.historyArr[indexPath.item];
    self.searchTF.text = str;
    [self searchData];
}

- (NSString *)detectLanguageForText:(NSString *)text{
    if (@available(iOS 11.0, *)) {
        NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:@[NSLinguisticTagSchemeLanguage] options:0];
        [tagger setString:text];
        NSString *language = [tagger dominantLanguage];
        return language;
    } else {
        return @"ja-JP";
    }
}

#pragma mark - 删除历史记录
-(void)deleteBtnClick{
    [self.historyArr removeAllObjects];
    [[NSUserDefaults standardUserDefaults]setObject:self.historyArr forKey:@"searchHistoryArr"];
    [self.collectionView reloadData];
}

#pragma mark - 取消搜索
-(void)cancelBtnClick{
    self.tableView.hidden = YES;
    self.searchTF.text = @"";
    [self.searchTF resignFirstResponder];
    [self.collectionView reloadData];
}

#pragma mark - 点击了搜索
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    if([self.historyArr containsObject:textField.text]){
        [self.historyArr removeObject:textField.text];
    }
    [self.historyArr insertObject:textField.text atIndex:0];
    if(self.historyArr.count > 10){
        [self.historyArr removeObjectsInRange:NSMakeRange(10,self.historyArr.count-10)];
    }
    [[NSUserDefaults standardUserDefaults]setObject:self.historyArr forKey:@"searchHistoryArr"];
    [self searchData];
    return YES;
}

-(void)textChange{
    [self searchData];
}

-(void)searchData{
    if(self.tableView.hidden == YES){
        self.tableView.hidden = NO;
    }
    self.searchWordManager.search = self.searchTF.text;
    if(self.chineseBtn.selected == YES){
        self.searchWordManager.mode = @"1";
    }else{
        self.searchWordManager.mode = @"0";
    }
    [self.searchWordManager loadData];
}

#pragma mark - tableview
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCollectionListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCollectionListCell"];
    if(indexPath.row < self.resultArr.count){
        cell.isSel = NO;
        WordListModel *model = self.resultArr[indexPath.row];
        cell.wordModel = model;
        __weak typeof(self)self_weak_ = self;
        __weak typeof(cell)cell_weak_ = cell;
        [cell setPlayBlock:^{
            //停止正在播放的
            [self_weak_ stopSpeaking];
            self_weak_.currentCell = cell_weak_;
            if(indexPath.row == self_weak_.playIndex){
                //暂停
                self_weak_.playIndex = -1;
            }else{
                //播放
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self_weak_.playIndex = indexPath.row;
                    if(model.audio&&![model.audio isEqualToString:@""]){
                        [self_weak_ playAudio:model.audio];
                    }else{
                        if((model.pronunciation)&&(![model.pronunciation isEqualToString:@""])){
                            if((model.writing)&&(model.isReadWriting)&&([model.isReadWriting isEqualToString:@"1"]||model.isReadWriting.integerValue == 1)){
                                [self_weak_ speakJapaneseText:model.writing];
                            }else{
                                [self_weak_ speakJapaneseText:model.pronunciation];
                            }
                        }else{
                            if((model.writing)&&(![model.writing isEqualToString:@""])){
                                [self_weak_ speakJapaneseText:model.writing];
                            }
                        }
                    }
                });
            }
        }];
    }
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.resultArr.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WordListModel *model = self.resultArr[indexPath.row];
    if([self.historyArr containsObject:model.writing]){
        [self.historyArr removeObject:model.writing];
    }
    [self.historyArr insertObject:model.writing atIndex:0];
    if(self.historyArr.count > 10){
        [self.historyArr removeObjectsInRange:NSMakeRange(10,self.historyArr.count-10)];
    }
    [[NSUserDefaults standardUserDefaults]setObject:self.historyArr forKey:@"searchHistoryArr"];
    
    [self stopSpeaking];
    
    WordDetialViewController *vc = [[WordDetialViewController alloc]init];
    vc.wordModel = model;
    JPNavigationController *nav = [[JPNavigationController alloc]initWithRootViewController:vc];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:nav animated:YES completion:nil];
    
}

#pragma mark - 播放读取文本
- (void)speakJapaneseText:(NSString *)text{
    
    [self listentTypeSet];
    
    if(self.currentCell){
        [self.currentCell startVoiceAnimation];
    }
    
//    if(!self.synthesizer){
//        self.synthesizer = [[AVSpeechSynthesizer alloc] init];
//        self.synthesizer.delegate = self;
//    }
//    AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:text];
//    utterance.rate = 0.53; // 语速，范围0.0~1.0
//    utterance.pitchMultiplier = 1.1; // 音高，范围0.5~2.0
//    utterance.volume = 1.0; // 音量，范围0~1
//    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"ja-JP"];
//    utterance.voice = voice;
//    [self.synthesizer speakUtterance:utterance];
    
    dispatch_async(self.work_queue, ^{
        // 如果上个任务没有合成完毕，手动取消，开始合成新的任务
        [self.nui nui_tts_cancel:NULL];
        
        [self UpdateTtsParams:text];

        [self.nui nui_tts_play:"1" taskId:"" text:[text UTF8String]];
    });
}

#pragma mark - 更新语音合成参数配置
-(void)UpdateTtsParams:(NSString *)content{
    
    int chars = 0;
    // 支持一次性合成300字符以内的文字，其中1个汉字、1个英文字母或1个标点均算作1个字符，
    // 超过300个字符的内容将会截断。所以请确保传入的text小于300字符(不包含ssml格式)。
    // 长短文本语音合成收费不同，请注意。
    // 300字这个截点可能会变更，以官网文档为准。
    chars = [self.nui nui_tts_get_num_of_chars: [content UTF8String]];
    if (chars > 300) {
        // 超过300字符设置成 长文本语音合成 模式
        [self.nui nui_tts_set_param:"tts_version" value:"1"];
    } else {
        // 未超过300字符设置成 短文本语音合成 模式
        [self.nui nui_tts_set_param:"tts_version" value:"0"];
    }
}

#pragma mark - tts callback
- (void)onNuiTtsEventCallback:(NuiSdkTtsEvent)event taskId:(char*)taskid code:(int)code{
//    TLog(@"onNuiTtsEventCallback event[%d]", event);
    if (event == TTS_EVENT_START) {
//        TLog(@"onNuiTtsEventCallback TTS_EVENT_START");
        // 启动播放器
        [self.audioController startPlayer];
    } else if (event == TTS_EVENT_END || event == TTS_EVENT_CANCEL || event == TTS_EVENT_ERROR) {
        if (event == TTS_EVENT_END) {
//            TLog(@"onNuiTtsEventCallback TTS_EVENT_END");
            // 注意这里的event事件是指语音合成完成，而非播放完成，播放完成需要由audioController对象来进行通知
            [self.audioController drain];
        } else {
            // 取消播报、或者发生异常时终止播放
            if(self.audioController){
                [self.audioController stopPlayer];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if(self.currentCell){
                    [self.currentCell stopVoiceAnimation];
                }
                self.playIndex =  -1;
            });
        }
        if (event == TTS_EVENT_ERROR) {
            const char *errmsg = [self.nui nui_tts_get_param: "error_msg"];
//            TLog(@"tts get errmsg:%s", errmsg);
            NSString *errorString = [NSString stringWithUTF8String:errmsg];
            if ([errorString containsString:@"144003"]) {
               //token过期
                [self.aLiYunTokenManager loadData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成token过期，已重新获取，请再次点击播放"];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成失败"];
                });
            }
        }
      
    }
}

- (void)onNuiTtsUserdataCallback:(char*)info infoLen:(int)info_len buffer:(char*)buffer len:(int)len taskId:(char*)task_id {
    TLog(@"onNuiTtsUserdataCallback info ...");
    if (info_len > 0) {
        TLog(@"onNuiTtsUserdataCallback info text %s. index %d.", info, info_len);
    }
    if (len > 0) {
        [self.audioController write:(char*)buffer Length:(unsigned int)len];
    }
}

-(void)onNuiTtsVolumeCallback:(int)volume taskId:(char*)task_id{
    
}

#pragma mark - Audio Player Delegate
-(void)playerDidFinish {
    //播放数据被实际播放完成后回调。
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.currentCell){
            [self.currentCell stopVoiceAnimation];
        }
        self.playIndex =  -1;
    });
}

//语音合成完成
-(void)playerDrainDataFinish{
   
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.audioController.isPlayerStopped == YES){
            if(self.currentCell){
                [self.currentCell stopVoiceAnimation];
            }
            self.playIndex =  -1;
        }
    });

}

#pragma mark - 停止当前正在读的文本
- (void)stopSpeaking{
    
//    if (self.synthesizer&&self.synthesizer.isSpeaking) {
//        [self.synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
//        if(self.currentCell){
//            [self.currentCell stopVoiceAnimation];
//        }
//    }
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
            }
        });
    }
    if(self.audioController){
        [self.audioController stopPlayer];
    }
    if(self.currentCell){
        [self.currentCell stopVoiceAnimation];
    }
    if(self.avPlayer){
        self.isPlaying = NO;
        [self.avPlayer pause];
        [self.avPlayer seekToTime:kCMTimeZero];
    }
}

#pragma mark - 单词音频播放
-(void)playAudio:(NSString *)audio{
    
    [self listentTypeSet];
    
    if(self.currentCell){
        [self.currentCell startVoiceAnimation];
    }
    
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:audio]];
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    if(self.avPlayer){
        [self.avPlayer pause];
        [self.avPlayer replaceCurrentItemWithPlayerItem:item];
    }else{
        self.avPlayer = [[AVPlayer alloc] initWithPlayerItem:item];
    }
    [self.avPlayer play];
    self.isPlaying = YES;
}

-(void)playToEndTime:(NSNotification*)notifi{
    if(self.currentCell){
        [self.currentCell stopVoiceAnimation];
    }
    self.playIndex =  -1;
    [self.avPlayer seekToTime:kCMTimeZero];
    self.isPlaying = NO;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey] integerValue];
        if (status == AVPlayerItemStatusReadyToPlay) {
            NSLog(@"播放成功");
            
        } else if (status == AVPlayerItemStatusFailed) {
            NSLog(@"播放失败");
            [JPProgressHUD showMsg:@"播放失败"];
            if(self.currentCell){
                [self.currentCell stopVoiceAnimation];
            }
            self.playIndex =  -1;
        }
    }
}

//#pragma mark - AVSpeechSynthesizer deletage
//- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
//    // 当前文本已经读完
//    if(self.currentCell){
//        [self.currentCell stopVoiceAnimation];
//    }
//    self.playIndex =  -1;
//}


#pragma mark - 设置静音模式下也能播放音频
-(void)listentTypeSet{
    // 获取当前的音频会话类别
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    
    // 检查当前类别是否已经是 AVAudioSessionCategoryPlayback
    if (![audioSession.category isEqualToString:AVAudioSessionCategoryPlayback]) {
        NSError *setCategoryError = nil;
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
        
        if (setCategoryError) {
            NSLog(@"Error setting category: %@", [setCategoryError localizedDescription]);
        }
    }
    
    // 检查音频会话是否已经处于激活状态
    if (!audioSession.isOtherAudioPlaying) {
        NSError *activationError = nil;
        [audioSession setActive:YES error:&activationError];
        
        if (activationError) {
            NSLog(@"Error activating session: %@", [activationError localizedDescription]);
        }
    }
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.searchWordManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [WordListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.resultArr = [NSMutableArray arrayWithArray:arr];
        [self.tableView reloadData];
    }
    
    if([manager isEqual:self.aLiYunTokenManager]){
         NSDictionary *dic = manager.response.content;
         if(dic[@"data"][@"token"]){
             NSString *token = [NSString stringWithFormat:@"%@",dic[@"data"][@"token"]];
             [[NSUserDefaults standardUserDefaults]setObject:token forKey:@"ALIYUN_YUYIN_TOKEN"];
         }
         if(dic[@"data"][@"expireTime"]){
             NSString *expireTime = [NSString stringWithFormat:@"%@",dic[@"data"][@"expireTime"]];
             [[NSUserDefaults standardUserDefaults]setObject:expireTime forKey:@"ALIYUN_YUYIN_EXPIRETIME"];
         }
         if (self.nui) {
            [self.nui nui_tts_release];
            self.nui = nil;
         }
         [self NuiTtsInit];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    // 若_nui未进行释放, 下次进入此view使用的_nui处于已初始化,
    // 则再调用nui_tts_initialize无法覆盖已经设置的参数.
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
    
    if(self.avPlayer&&self.isPlaying == YES){
        [self.avPlayer pause];
        self.isPlaying = NO;
    }
    
}


@end
